package com.yonyougov.devops.cruxcisupport;

import com.yonyougov.devops.cruxcisupport.common.vo.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ResultMsg exceptionHandler(HttpServletResponse response, Exception e) {
        log.error(e.getMessage(), e);
        //绑定异常是需要明确提示给用户的
        if (e instanceof SQLIntegrityConstraintViolationException) {
            ResultMsg msg = ResultMsg.getInstance(500, "字段唯一");
            msg.getExtMsg().put("ex", e);
            return msg;
        }
        response.setStatus(500);
        ResultMsg msg = ResultMsg.getInstance(500, e.getMessage());
        msg.getExtMsg().put("ex", e.getMessage());
        return msg;
    }
}
